package com.worldstear.controller;

import com.worldstear.core.R;
import com.worldstear.core.shiro.ShiroSessionManager;
import com.worldstear.model.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
public class LoginController {
    @RequestMapping ("/login")
    public R<Map<String, Object>> login(User user, HttpServletRequest request) {
        if(!Objects.equals(request.getMethod(), "POST")) {
            throw new AuthenticationException("用户未登录");
        }
        if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())) {
            return R.error("请输入用户名和密码！");
        }
        //用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getUserName(),
                user.getPassword()
        );
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            log.error("用户名不存在！", e);
            return R.error("用户名不存在！");
        } catch (AuthenticationException e) {
            log.error("账号或密码错误！", e);
            return R.error("账号或密码错误！");
        } catch (AuthorizationException e) {
            log.error("没有权限！", e);
            return R.error("没有权限");
        }
        return R.success(Collections.singletonMap(ShiroSessionManager.AUTHORIZATION, request.getAttribute(ShiroSessionManager.AUTHORIZATION)));
    }

    @RequiresRoles("admin")
    @GetMapping("/admin")
    public String admin() {
        return "admin success!";
    }

    @RequiresPermissions("obj")
    @GetMapping("/index")
    public String index() {
        return "index success!";
    }

    @RequestMapping("/unauthorized")
    public R unauthorized() {
        return R.error("用户未登录");
    }

}
